package cz.proks.schoolpupilbook.gwt.core.handler;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;

import cz.proks.schoolpupilbook.gwt.core.ResultNotifiable;
import cz.proks.schoolpupilbook.gwt.service.MarkService;
import cz.proks.schoolpupilbook.gwt.service.ServiceFactory;
import cz.proks.schoolpupilbook.gwt.widget.common.MarkForm;
import cz.proks.schoolpupilbook.gwt.widget.common.MarkForm.SubmitEvent;
import cz.proks.schoolpupilbook.shared.domain.Course;
import cz.proks.schoolpupilbook.shared.domain.Mark;
import cz.proks.schoolpupilbook.shared.domain.User;

public class MarkFormHandler implements MarkForm.SubmitEvent.SubmitEventHandler{
	@Override
	public void onSubmit(SubmitEvent event) {
		MarkService markService = ServiceFactory.getMarkService();
		Mark mark = createMark(event);
		
		markService.save(mark, new ResultNotifiable<Void>() {
			
			@Override
			public void onSucces(Void object) {
				History.back();
				
			}
			
			@Override
			public void onError(Throwable t) {
				Window.alert("Failed to save mark: " + t.getLocalizedMessage());				
			}
		});		
	}
	
	private Mark createMark(SubmitEvent event) {
		Mark mark = new Mark();
		
		User lector = new User();
		User student = new User();
		Course course = new Course();
		
		lector.setId(event.getLectorId());
		student.setId(event.getStudentId());
		course.setId(event.getCourseId());
		
		mark.setId(event.getId());
		mark.setTime(event.getTime());
		mark.setLector(lector);
		mark.setStudent(student);
		mark.setCourse(course);
		mark.setMark(event.getMark());
		mark.addComment(lector, event.getTime(), event.getInitialComment());
		
		return mark;
	}
}
